/*
 * @(#)ChineseKaptcha.java 2014-9-30 上午10:37:22
 * Copyright 2014 鲍建明, Inc. All rights reserved. 8637.com
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hengxin.bean;

import java.io.UnsupportedEncodingException;
import java.util.Random;

import cn.singno.bob.constant.Chartset;

import com.google.code.kaptcha.text.TextProducer;
import com.google.code.kaptcha.util.Configurable;

/**
 * <p>名称：ChineseKaptcha.java</p>
 * <p>描述：随机中文验证码</p>
 * <pre>
 *    
 * </pre>
 * @author 鲍建明
 * @date 2014年9月17日 下午5:30:39
 * @version 1.0.0
 */
public class ChineseKaptcha extends Configurable  implements TextProducer 
{

	/**
	 * 
	 * <p>描述：随机获取4位验证码，中英文混合 </p>
	 * <pre>
	 *    
	 * </pre>
	 * @return
	 */
	@Override
	public String getText()
	{
		int length = getConfig().getTextProducerCharLength();  
        char[] chars = getConfig().getTextProducerCharString();  
        String finalWord = "", firstWord = "";  
        String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",  
                "a", "b", "c", "d", "e", "f" };  
  
        Random rand = new Random();  
  
        for (int i = 0; i < length; i++) {  
            switch (rand.nextInt(3)) {  
            case 1:  
                firstWord = String.valueOf(chars[rand.nextInt(chars.length)]);  
                break;  
            case 2:  
            	firstWord = getChinese(rand, array);
                break;  
            default:  
                firstWord = String.valueOf(chars[rand.nextInt(chars.length)]);  
                break;  
            }  
            finalWord += firstWord;  
        }  
        return finalWord;  
	}
	
	/**
	 * 获取随机的中文字符
	 * @param rand
	 * @param array
	 * @return
	 */
	public String getChinese(Random rand,  String[] array){
		 int r1,  
         r2,  
         r3,  
         r4;  
         String strH,  
         strL;// high&low  
         r1 = rand.nextInt(3) + 11; // 前闭后开[11,14)  
         if (r1 == 13) {  
             r2 = rand.nextInt(7);  
         } else {  
             r2 = rand.nextInt(16);  
         }  

         r3 = rand.nextInt(6) + 10;  
         if (r3 == 10) {  
             r4 = rand.nextInt(15) + 1;  
         } else if (r3 == 15) {  
             r4 = rand.nextInt(15);  
         } else {  
             r4 = rand.nextInt(16);  
         }  

         strH = array[r1] + array[r2];  
         strL = array[r3] + array[r4];  

         byte[] bytes = new byte[2];  
         bytes[0] = (byte) (Integer.parseInt(strH, 16));  
         bytes[1] = (byte) (Integer.parseInt(strL, 16));  

         try {  
             return new String(bytes, Chartset.UTF8);  
         } catch (UnsupportedEncodingException e) {  
             e.printStackTrace();  
         }  
		return "";
	}
	

}
